package com.neuedu.his.service;

import com.neuedu.his.dao.UploadDao;
import com.neuedu.his.entity.Upload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * 项目：      his
 * 类名:       FileService
 * 创建时间：  2023/12/21 11：28
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
public class FileService {

    private UploadDao uploadDao = new UploadDao();



    private static  final  String UPLOAD_DIR = "D:\\histupload\\";


    public Map upload(HttpServletRequest request) {

        Map map = new HashMap();
        map.put("success",false);

        /**
         * 上传操作
         */
        //判断是否支持  Multipart
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            //设置 Tomcat 接收到 文件 存放到那个临时目录
            ServletContext servletContext = request.getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

            //解析 Request的流

            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {


                    String name = fileItem.getName();// package.png
                    String fieldName = fileItem.getFieldName();  //abc
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    String ext = name.substring(name.lastIndexOf("."));

                    String newFileName = uuid + ext;
                    File dist = new File(UPLOAD_DIR + newFileName);


                    fileItem.write(dist);//讲文件 从临时目录 转出到   D;\\upload


                    Upload upload = new Upload();
                    upload.setExt(ext);
                    upload.setOriginName(fieldName);
                    upload.setPath(newFileName);
                    upload.setUpTime(new Date());
                    upload.setUpUser("admin");
//                    upload.setUpType();


                    uploadDao.insert(upload);

                    map.put("success",true);
                    map.put("id",upload.getUploadId());
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }


        return map;
    }

    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String uploadId = request.getParameter("uploadId");
        Upload upload = uploadDao.selectOne(" where upload_id = ?", uploadId);



        response.addHeader("Content-Disposition","inline;");



        File file = new File(UPLOAD_DIR + upload.getPath());
        FileInputStream is = new FileInputStream(file);
        ServletOutputStream os = response.getOutputStream();
        byte bytes[] = new byte[1024];
        int len = -1;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
            os.flush();
        }
        os.close();
        is.close();
    }
}
